﻿using System;
using System.Collections;
using Unity.VisualScripting;
using UnityEngine;


public class Dashing : MonoBehaviour
{
    [Header("references")]
    public Transform orientation;
    public Transform playerCamera;
    private Rigidbody rb;
    private PlayerMovement playerMovement;

    [Header("dashing")]
    public float dashForce;
    public float dashUpwardForce;
    public float dashDuration;

    [Header("cooldown")]
    public float dashCd;
    public float dashCdTimer;

    [Header("Input")]
    public bool dashRequest;
    public Vector2 inputDirection;
    public bool allowAllDirections;
    public bool useCameraForward;
    public bool disableGravity;
    public bool resetVal;
    private void Start()
    {
        rb = GetComponent<Rigidbody>();
        playerMovement = GetComponent<PlayerMovement>();

        playerMovement.OnDashAction += OnDashHandler;
    }
    private void OnApplicationQuit()
    {
        playerMovement.OnDashAction -= OnDashHandler;
    }
    private void OnDashHandler(bool obj)
    {
        dashRequest = obj;
    }

    private void Update()
    {
        if (dashRequest)
        {
            Dash();
        }
        if(dashCdTimer > 0)
        {
            dashCdTimer -= Time.deltaTime;
        }
    }
    private void Dash()
    {
        if(dashCdTimer > 0)
        {
            return;
        }
        else
        {
            dashCdTimer = dashCd;
        }
        Transform forwardT;
        playerMovement.dashing = true;
        if (useCameraForward)
        {
            forwardT = playerCamera;
        }
        else
        {
            forwardT = orientation;
        }

        Vector3 direction = GetDirection(forwardT);

        Vector3 forceToApply = direction * dashForce + orientation.up * dashUpwardForce;
        if (disableGravity)
        {
            rb.useGravity = false;
        }
        delayedForceToApply = forceToApply;
        Invoke("DelayedDashForce", 0.025f);
        Invoke("ResetDash", dashDuration);
    }
    private Vector3 delayedForceToApply;
    private void DelayedDashForce()
    {
        if (resetVal)
        {
            rb.velocity = Vector3.zero;
        }
        rb.AddForce(delayedForceToApply, ForceMode.Impulse);
    }
    private void ResetDash()
    {
        playerMovement.dashing = false;
        if (disableGravity)
        {
            rb.useGravity = true;
        }
    }
    private Vector3 GetDirection(Transform forwardT)
    {
        inputDirection = playerMovement.inputDirection;
        Vector3 direction = Vector3.zero;
        if (allowAllDirections)
        {
            direction = forwardT.forward * inputDirection.y + forwardT.right * inputDirection.x;
        }
        else
        {
            direction = forwardT.forward;
        }
        if (inputDirection.magnitude == 0)
        {
            direction = forwardT.forward;
        }
        return direction.normalized;
    }
}
